package com.wisdom.core.netty.handler.server;

import com.alibaba.fastjson.JSON;
import com.wisdom.core.data.RpcRequest;
import com.wisdom.core.exception.RpcException;
import com.wisdom.core.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @description: <将请求数据解码为RpcRequest对象 二次解码器>
 * @author: Leo
 * @date:2021-08-22 15:12
 */
@Slf4j
public class RpcRequestDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
        /*
            此处不释放 ByteBuf  因 MessageToMessageDecoder 的 channelRead方法对 ByteBuf 进行了释放
         */
        try {
            int length = byteBuf.readableBytes();
            byte[] bytes = new byte[length];
            byteBuf.readBytes(bytes);
            RpcRequest rpcRequest = ProtostuffUtil.deserialize(bytes, RpcRequest.class);
            log.info("server received msg, msg is {}", JSON.toJSONString(rpcRequest));
            out.add(rpcRequest);

        } catch (Exception e) {
            log.error("RpcRequestDecoder decode error, msg is {}", e.getMessage());
            throw new RpcException(e.getMessage(), e);
        }

    }


}
